import { Builder, Nuxt } from 'nuxt'
import cookieParser from 'cookie-parser'
import bodyParser from 'body-parser'
import express from 'express'
import vueAxios from 'axios'
// import ps from 'ps'

vueAxios.defaults.withCredentials = true

const app = express()
const router = express.Router()

// Import and Set Nuxt.js options
let config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')

const host = process.env.HOST || '0.0.0.0'
const port = process.env.PORT || 8888

app.set('port', port)

app.use(bodyParser.json())
app.use(cookieParser())


// Init Nuxt.js
const nuxt = new Nuxt(config)

// Build only in dev mode
if (config.dev) {
    const builder = new Builder(nuxt)
    builder.build()
}

const axios = vueAxios.create({
    // 用于请求后台 API 的 baseURL
    baseURL: process.env.API_SERVER_URL
})

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

axios.interceptors.request.use(config => {
    if (config.url[config.url.length - 1] !== '/') {
        config.url += '/'
    }    
    
    return config
}, err => {
    return Promise.reject({ status: false, code: 500, msg: 'config error' })
})

axios.interceptors.response.use(response => {
    return response.data || {}
}, err => {
    const errResp = err.response || {}
    const errMsg = {
        code: errResp.status,
        msg: errResp.statusText,
        status: false,
        data: errResp.data
    }
    return Promise.reject(errMsg)
})

router.get('/*', (req, res) => {
    const url = `/api/${req.params['0']}`
    const headers = axios.defaults.headers || {}

    if (req.cookies.token) {
        axios.defaults.headers.common["Authentication"] = req.cookies.token
    } else {
        delete axios.defaults.headers.common["Authentication"]
    }

    axios.get(url, {
        headers,
        params: req.query
    })
    .then(response => {
        res.status(200)
        res.json(response)
    }).catch(err => {
        err.code = err.code || 500
        res.status(err.code || 500)
        res.json(err)
    })
})
  
router.post('/*', (req, res) => {
    const url = `/api/${req.params['0']}`
    const headers = axios.defaults.headers || {}

    headers['Content-Type'] = 'application/x-www-form-urlencoded'

    if (req.cookies.token) {
        axios.defaults.headers.common["Authentication"] = req.cookies.token
    } else {
        delete axios.defaults.headers.common["Authentication"]
    }

    axios.post(url, JSON.stringify(req.body), { headers }).then(response => {        
        res.status(200)
        res.json(response)
    }).catch(err => {
        err.code = err.code || 500
        res.status(err.code || 500)
        res.json(err)
    })
})

// 如果使用代理
if (+process.env.AXIOS_PROXY === 1) {
    // app.use('/api/v/', router)
    console.log('router:::',router)
    app.use('/api/', router)
}

app.use(nuxt.render)

// Listen the server
app.listen(port, host)
console.log('Server listening on ' + host + ':' + port) // eslint-disable-line no-console
